var datatable;// 定义一个全局的dataTable
var deviceStr;
var signalJson;
var rsid;
var userid;
var preDt;
var lineLength=100;//
var pageData;
var dataLength;
var totalPages;
var deviceJson;
var topRecordCount;
var defaultImageName="default.png";
$(function() {
//	$("#table_previous").attr("class","paginate_button previous");
//	$("#table_next_new").click(function(){
//		//重新绑定下一页事件
//		var curPage=$("#currentPage").val();
//		$("#currentPage").val(Number(curPage)+1);
//		alert($("#currentPage").val());
//		getList();
//	});
//	$("#table_previous_new").click(function(){
//		//重新绑定上一页事件
//		var curPage=$("#currentPage").val();
//		$("#currentPage").val((curPage-1));
//		getList();
//	});
	$("#table_paginate_new,#table_info_new").hide();
	$('#table_length_new').on('change', function() {
		$("#currentPage").val("1");
		getList();
	});
//	$("#phoneNumber").val("18611836535");//赋初始值方便测试
//	$("#beginDate").val("2015-10-01 10:33:23")
//	$("#endDate").val("2015-12-01 10:33:23")
	
	if($("#queryTypeInfo").val() == '2'){//表示电话号码为空
		$("#queryType").find("option[value='2']").attr("selected",true);
	}
	
	if($("#phoneNumber").val()!=""&&$("#beginDate").val().trim()&&$("#endDate").val().trim()){
		getList();
	}else{
//		$("#phoneNumber").val("18611836535");//赋初始值方便测试
	}
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});
	$('#table tbody').on('dblclick', 'tr', function() {
		var infoElementStr=$(this).attr("elements");
		showDetail(infoElementStr);
//		$("#infoElements").val(infoElementStr);
//		$("#textid").text(infoElementStr);
//		infoFormSubmit();
		
	});
	
})

/**
 * 点击箭头的onclick事件
 */
function getElements(rowIndex){
	var trObj=$("#table  tbody").find("tr").eq(rowIndex);//
	var elements=trObj.attr("elements");
//	$("#infoElements").val(elements);
//	$("#textid").text(elements);
//	infoFormSubmit();
	showDetail(elements);
}
/**
 * 获取表格数据
 */
function getList(fromPage) {
	if(!fromPage){
		$("#currentPage").val("1");
	}
	var phoneNumber=$("#phoneNumber").val().trim();
	var beginDate=$("#beginDate").val().trim();
	var endDate=$("#endDate").val().trim();
	var currentPage=$("#currentPage").val();
	var pageSize=$("#table_length_select").val();
    var queryType=$("#queryType").val();
    
    if(queryType=="1"){
    	//号码
    	if(phoneNumber==""){
    		alert("请输入手机号码！");
    		return ;
    	}
    	if(phoneNumber.length!=11){
    		alert("请输入正确的手机号码！");
    		return ;
    	}
    	var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; 
	    if(!myreg.test(phoneNumber)) {
	    	alert("请输入正确的手机号码！");
    		return ;
	    }
    }
    if(queryType=="2"){
    	//imsi
    	if(phoneNumber==""){
    		alert("请输入IMSI!");
    		return;
    	}
    }
	if(beginDate==""){
		alert("请输入开始时间！");
		return;
	}
	if(endDate==""){
		alert("请输入结束时间！");
		return;
	}
	
	var beginDate1 = new Date(beginDate.replace(/-/g,"/"));
	var endDate2 = new Date(endDate.replace(/-/g,"/"));
	if((beginDate1-endDate2)>=0){
		alert("开始时间不能大于或等于结束时间！");
		return;
	}
	if(!checkInterval()){
		alert("时间间隔不能大于2小时！");
		return;
	}
//	if(null!=paramImsi && paramImsi!=""){
//		//如果传过来有imei，则不查用户相关信息，直接往下走
//		userid=paramImsi;
//		$("#IMSIId").val(paramImsi);
//		$("#phoneNumber").val(paramImsi);
//	}else{
	  if(queryType=="1"){
			 $.ajax({  
		         async:false,//使用同步的Ajax请求  
		          type: "POST",  
		          dataType: "json",
		          url: "../../kpi/signalBackTrack/getUserInfo?",  
		          data: {"phoneNumber":phoneNumber,"queryType":queryType},  
		          success: function(msg){  
		          userid=msg.imsi;
		          $("#IMSIId").val(msg.imsi);
		          $("#phoneNbr").val(msg.acc_nbr);
		          var areaName="";
		          for(var m=0;m<zNodes.length;m++){
		        	  var json=zNodes[m];
		        	  if(json.id==msg.city_code){
		        		  areaName=json.name;
		        		  break;
		        	  }
		          }
		          $("#areaName").val(areaName);
		          $("#terminal").val(msg.terminal_brand);
		          },
		          error:function(msg){
		        	  alert(msg.msg);
		          }
		      }); 
	  }else{
		  userid=phoneNumber;
	  }
	
	
	if(null==userid ||userid==''){
		$("#showInfo").show();
		$("#table2").empty();
		$("#table tbody").empty();
		document.getElementById("rightDiv").style["overflow-x"]="hidden";
		$("#showTopRecord").text("0");
		$("#showRecordBegin").text("0");
		$("#showRecordEnd").text("0");
		alert("查询不到相关的用户信息！");
		return;
	} 
	document.getElementById("rightDiv").style["overflow-x"]="auto";
	$("#table tbody tr").remove();
	if (datatable == undefined || datatable == "undefined" || datatable == null) {
	} else {
		datatable.fnDestroy();
	}
	$("#showInfo").show();
	$("#table2").empty();
	datatable = $('#table').dataTable({
		"bPaginate" : false, // 翻页功能
		"bLengthChange" : false, // 改变每页显示数据数量
		"bFilter" : false, // 过滤功能
		"bSort" : false, // 排序功能
		"bInfo" : false,// 页脚信息
		"bAutoWidth" : true,// 自动宽度
		// "sPaginationType": "full_numbers",//显示分页的样式 还有simple_numbers等
		 "fnDrawCallback": function (oSettings) {
			 drawContent();
			 dealPage();
			 },
		 "fnCreatedRow": function( nRow, aData, iDataIndex ) {
			 	  nRow.setAttribute('fromToId',aData.fromToId); 
			      nRow.setAttribute('elements',aData.infoElementList); 
			    },
		"sScrollX" : "100%",
		"bScrollCollapse" : true,
		"oLanguage" : {
			"sLengthMenu" : "每页显示 _MENU_条",
			"sZeroRecords" : "没有找到符合条件的数据",
			"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
//			"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
			"sInfo" : "共计 _TOTAL_ 条",
			"sInfoEmpty" : "没有记录"
		},
		"bProcessing" : true,
		"bServerSide" : false,
		 "ajax": {
			    "url": "../../kpi/signalBackTrack/getData",
			    "type": "POST",
			    "data" : {
					"currentPage" : currentPage,
					"pageSize":pageSize,
					"userid":userid,
					"beginDate" : beginDate,
					"endDate" : endDate
				},
			    "dataSrc": function ( resp ) 
			    {
			    	var info=resp.info;
					if(info.result!='0'){
						$(".dataTables_processing").css("display","none");
						$(".dataTables_scrollHeadInner th").css("background-color","#EEEEEE");
						rsid="";
						preDt="";
						topRecordCount=0;
						$("#table tbody tr").remove();//删除loading
						$("#table_paginate_new,#table_info_new").hide();
						$("#showInfo").show();
						var errorMsg=info.message;
						if(errorMsg.indexOf("Connection refused")!=-1){
							alert("信令回溯服务连接异常！");
						}else{
						alert(info.message);
						}
						totalPages=0;
					}else{
						$("#table_paginate_new,#table_info_new").show();
						$("#showTopRecord").text(resp.topRecordCount);
						$("#showRecord").text(resp.recordCount);
						var localCount=resp.recordCount;
						topRecordCount=resp.topRecordCount;
						var size=$("#table_length_select").val();
						var curpage=$("#currentPage").val();
						var beginCount=(curpage-1)*size+1;
						if(localCount==0)
							beginCount=0;
						var endCount=(curpage-1)*size+localCount;
						$("#showRecordBegin").text(beginCount);
						$("#showRecordEnd").text(endCount);
						totalPages=Math.ceil(resp.topRecordCount / size); 
						deviceStr=resp.deviceStr;
						dataLength=resp.allData.length;
						deviceJson=resp.deviceJson;
						if(null!=deviceJson && deviceJson.length>0&&dataLength>0){
							signalJson=resp.allData;
							rsid=info.id;
							preDt=resp.preDt;
							$("#showInfo").hide();
							document.getElementById("rightDiv").style.overflow="auto";
						}else{
							$("#showInfo").show();
							var rightWidth=$("#rightDiv").width();
							//document.getElementById("rightDiv").style.overflow="hidden";
						}
					}
					$(".dataTables_scrollHeadInner").css("background-color","#EEEEEE");
					return resp.allData;
			    }  
			  },

		columns : [ {
			data : "date-pre"
		}, {
			data : "date-sub"
		}, {
			data : "from-to-name"
		}, {
			data : "msg-type"
		}, {
			data : "device-from-name"
		}, {
			data : "Src"
		}, {
			data : "device-to-name"
		}, {
			data : "Dst"
		}  ]

	});
}
/**
 * 图片没有找到，默认显示
 */
function imageNoFound(){
	var img=event.srcElement;
    img.src=imagePath+defaultImageName;
    img.onerror=null; 
}
/**
 * 画图形
 */
function drawContent(){
	if(deviceJson==undefined || deviceJson== "undefined" || deviceJson.length==0 ||dataLength==0){
		$("#table2").empty();
		return;
	}
	var rightDivWidth=$("#rightDiv").width();
	var leftDivWidth=$("#leftDiv").width();
	if(leftDivWidth<=initLeftWidth){
		//如果大于初始化的宽度，
//		$("#rightDiv").css("position","");
		document.getElementById("rightDiv").style.position="";
		$("#rightDiv").css("width",1000-leftDivWidth);
	}else{
		$("#cc").text(document.getElementById("rightDiv").style.position);
		document.getElementById("rightDiv").style.position="absolute";
//		$("#rightDiv").css("position","absolute");
		$("#rightDiv").css("width",initRightWidth);
	}
	
//	alert(rightDivStyleObject);
//	alert(rightDivStyleObject.attr("position"));
//	$("#rightDiv")
	$("#showInfo").hide();
	var propertityObj=new Object();
	var rowDataIndex=0;
	$("#table2").empty();
	var thHeight=$("#table3").height();
//	var scrollHieght=$(".dataTables_scrollHeadInner tr th").height();
//	alert(scrollHieght);
//	var pageHeight=$("#table_length").height();
//	deviceStr=deviceStr.substring(0,deviceStr.length-1);
	var str="";
	var deviceLength=deviceJson.length;
	var tableWidth=deviceLength*lineLength;
	var threadHeight=$("#table3 thead").height();
	for(var m=0;m<deviceLength;m++){
		var localJson=deviceJson[m];
		var id=localJson.id;
		var name=localJson.name;
		var type=localJson.type.toLowerCase();
		propertityObj[id]=m;
		str+='<th width='+lineLength+' height='+(thHeight+15)+' class="tableTh" id=col'+id+' style=word-break: break-all; word-wrap:break-word;><img width=50px height=40px onerror=imageNoFound();  src='+imagePath+type+'.png'+'></img><br/><font size=2>'+name+'</font></th>';
	}
	$("#table2").append(str);
	$("#table2").css("width",tableWidth);
//	var colsArray=deviceStr.split(",");
//	if(colsArray.length>1){
//		var tableWidth=colsArray.length*lineLength;
//		var threadHeight=$("#table3 thead").height();
//			for(var j=0;j<colsArray.length;j++){
//				propertityObj[colsArray[j]]=j;
//				str+='<th width='+lineLength+' height='+(thHeight+threadHeight-5)+' class="tableTh" id=col'+j+' style=word-break: break-all; word-wrap:break-word;>'+colsArray[j]+'</th>';
//			}
//		$("#table2").append(str);
//	}
	var objPropertyLength=Object.getOwnPropertyNames(propertityObj).length;//对象属性的个数
	$("#table tr").find('td').each(function(){
		if($(this).index()==2){
		var text=$(this).text();
//		var tdHeight=$(this).height();
		var tdHeight=$(this).parent().height();
		if(null==text||text=="" ||text.indexOf("->")==-1){
		var tempStr="";
		for(var m=0;m<deviceLength;m++){
			tempStr+="<td width='"+lineLength+"' height="+tdHeight+"></td>";
		}	
		$("#table2").append('<tr class="tableTr">'+tempStr+'</tr>');
		
		}else{
		//$("#table2").append('<tr><td width="100px"><svg width="100px" height="25px"><line x1="0" y1="0" x2="94" y2="0"  stroke="black" stroke-width="1" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"  /></svg></td><td width="100px"></td><td width="100px"></td><td width="100px"></td><td width="100px"></td></tr>');
//		var array=text.split("->");
		var fromToId=$(this).parent().attr("fromToId");		
		var array=fromToId.split(",");	
		var from=array[0];
		var to=array[1];
		var lineFromIndex=propertityObj[from];
		var lineToIndex=propertityObj[to];
		var val=lineToIndex-lineFromIndex;
		var absVal=Math.abs(val);//绝对值
		var trStr='';
		var preTdStr='';//箭头前的td
		var subfixTdStr='';//箭头后的td
		var drawStr='';//箭头str
		var times=calaTimes(rowDataIndex);
		if(val>0){
		//生成正方向的箭头
		 //先计算箭头左边td
		 for(var i=0;i<lineFromIndex;i++){
		 preTdStr+='<td width='+lineLength+' height='+(tdHeight)+'></td>';
		 }
		 //计算箭头
		 drawStr='<td  height='+(tdHeight)+' width='+lineLength+'><font size=2>'+times+'</font><svg onclick="getElements('+rowDataIndex+')" width='+lineLength+' height="1px"><line x1="2" y1="0" x2="'+((absVal+1)*lineLength-10)+'" y2="0"  stroke="black" stroke-width="1" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)" style="cursor:pointer;"  /></svg></td>';
		 //计算箭头右边的td
		  for(var k=1;k<=objPropertyLength-lineFromIndex-1;k++){
		 subfixTdStr+='<td  height='+(tdHeight)+' width='+lineLength+'></td>';
		 }
		 trStr="<tr  class='tableTr'>"+preTdStr+drawStr+subfixTdStr+"</tr>";
		 $("#table2").append(trStr);
		}else{
		//生成反方向箭头
		 //先计算箭头左边td
		 for(var i=0;i<lineToIndex;i++){
		 preTdStr+='<td  height='+(tdHeight)+' width='+lineLength+'></td>';
		 }
		 //计算箭头
		 drawStr='<td  height='+(tdHeight)+' width='+lineLength+'><font size=2>'+times+'</font><svg onclick="getElements('+rowDataIndex+')" width='+lineLength+' height="1px"><line x1="'+((absVal+1)*lineLength-4)+'" y1="0" x2="'+((absVal+1)*2+4)+'" y2="0"  stroke="black" stroke-width="1" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)" style="cursor:pointer;"  /></svg></td>';
		 //计算箭头右边的td
		  for(var k=1;k<=objPropertyLength-lineToIndex-1;k++){
		 subfixTdStr+='<td  height='+(tdHeight)+' width='+lineLength+'></td>';
		 }
		 trStr="<tr  class='tableTr'>"+preTdStr+drawStr+subfixTdStr+"</tr>";
		 $("#table2").append(trStr);
		}
		
			//$("#table2").append('<tr><td width="100px"><font size="2px;">400ms</font><svg width="100px" height="2px"><line x1="0" y1="0" x2="94" y2="0"  stroke="black" stroke-width="1" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"  /></svg></td><td width="100px"></td><td width="100px"></td><td width="100px"></td><td width="100px"></td></tr>');
		rowDataIndex++;
		}
		
		}
	});
	}
	/**
	 * 重写分页
	 */
	function dealPage(){
//		paginate_button previous disabled
//		paginate_button next disabled
//		$(".paginate_button").hide();
		$("#table_length").empty();//将原先分页隐藏
		$(".ellipsis").hide(); //将分页的...隐藏
		var tempLen=$(".paginate_button").length;
		$(".paginate_button").each(function(i){
			if(i==0 || i==tempLen-1)
			{
				$(this).show();
			}else{
				$(this).hide();
			}
		});
		
		var curPage=$("#currentPage").val();
		$("#table_previous").attr("class","paginate_button previous").attr("onclick","pageBefore(0)").attr("id","table_previous_new");
		if(curPage=="1"){
			$("#table_previous_new").addClass("disabled");
		}
		$("#table_next").attr("class","paginate_button next").attr("onclick","pageBefore(1)").attr("id","table_next_new");//绑定时间应该被分页覆盖了，所以写成attr onclick了
		
		//计算总页数
		
		if(totalPages==0){
			$("#table_next_new").addClass("disabled");
			$("#table_previous_new").addClass("disabled");
		}
		if(curPage==1){
			$("#table_next_new").removeClass("disabled");
			$("#table_previous_new").addClass("disabled");
		}
		if(curPage==totalPages){
			$("#table_next_new").addClass("disabled");
			if(curPage==1){
				$("#table_previous_new").addClass("disabled");
			}else{
				$("#table_previous_new").removeClass("disabled");
			}
		}
		if(dataLength==0){
			$("#table_next_new").addClass("disabled");
			$("#table_previous_new").addClass("disabled");
		}
	}
	function pageBefore(val){
		var curPage=$("#currentPage").val();
		curPage=Number(curPage);
		if(val==0){
			if(curPage==1)
				return;
			curPage=curPage-1;
		}
		if(val==1){
			if(curPage==totalPages)
				return;
			curPage=curPage+1;
		}
		$("#currentPage").val(curPage);
		getList(true);
	}
//	function drawHead(headStr){
//		var str="";
//		var colsArray=headStr.split(",");
//		if(colsArray.length>1){
//			var tableWidth=colsArray.length*100;
//			$("#table2").css("width",tableWidth);
//				for(var j=0;j<colsArray.length;j++){
//					propertityObj[colsArray[j]]=j;
//					str+='<th width=100 height=300 class="tableTh" id=col'+j+' style=word-break: break-all; word-wrap:break-word;>'+colsArray[j]+'</th>';
//				}
//			$("#tableThread").append(str);
//		}
//	}
/**
 * 计算箭头上的秒数
 */
	function calaTimes(rowDataIndex){
		var currentPage=$("#currentPage").val();
		var result;
		if(rowDataIndex<signalJson.length && rowDataIndex!=0){
			
			var a=Number(signalJson[rowDataIndex].dt);
			var b=Number(signalJson[rowDataIndex-1].dt)
			//alert("rowIndex:"+rowDataIndex+":"+signalJson[rowDataIndex]["date-sub"]);
			result= (a-b)+"ms";  
		}else{
			if(rowDataIndex==0 && currentPage!='1'){
				//如果是不是第一页并且第一条，去上条记录的dt
				var a=Number(signalJson[rowDataIndex].dt);
				var b=Number(preDt)
				//alert("rowIndex:"+rowDataIndex+":"+signalJson[rowDataIndex]["date-sub"]);
				result= (a-b)+"ms";  
			}else{
				result= "";
			}
		}
		return result;
	}
function testa(){
	var currentPage=$(".current").text();
	var pageSize=$("select[name=table_length]").val();
//	alert($(".paginate_button current").text())
//	var currentPage=$(".paginate_button current").attr("data-dt-idx");
//	//var pageSize=$("select")["name=table_length"][0].val();
//	alert(currentPage);
	//alert(pageSize);
}

/**
 * 协议栈解析
 */
function infoFormSubmit(){
		var url="../../kpi/signalBackTrack/getInfoElementList?rand="+ Math.random();
		$('#infoForm').attr("target","_blank").attr("action", url).submit();
	}
/**
 * 导出
 */
function exportPcap(){
	if(null==rsid||rsid==""){
		alert("请先点击查询或无记录可导出！");
		return;
	}
//	var currentPage=$(".current").text();
//	var pageSize=$("select[name=table_length]").val();
	var currentPage=$("#currentPage").val();
	var pageSize=$("#table_length_select").val();
//	var url="../../kpi/signalBackTrack/export?rand="+ Math.random()+"&rsid="+rsid+"&pageSize="+pageSize+"&currentPage="+currentPage;
	var url="../../kpi/signalBackTrack/export?rand="+ Math.random()+"&rsid="+rsid+"&recordCount="+topRecordCount;
	window.location.href=url;
}

function showDetail(path){
	var url="/kpi/signalBackTrack/getInfoElementList?rand="+ Math.random()+"&path="+path;
//	alert(url);
	linkTab("协议栈信息",url);
	//
}
function checkInterval(){
	var startTime=$("#beginDate").val();  
    var start=new Date(startTime.replace("-", "/").replace("-", "/"));  
    var endTime=$("#endDate").val();  
    var end=new Date(endTime.replace("-", "/").replace("-", "/"));  
    
    var interval=end-start;
    var time=60*60*2*1000;
    if(interval>time){
    	return false;
    }
    return true;
}